<template>
  <view class="edit-page dict-data-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="字典标签" name="dictLabel" required>
          <uni-easyinput
              v-model="form.dictLabel"
              placeholder="请输入字典标签"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="字典键值" name="dictValue" required>
          <uni-easyinput
              v-model="form.dictValue"
              placeholder="请输入字典键值"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="字典排序" name="dictSort" required>
          <uni-number-box
              v-model="form.dictSort"
              :min="0"
              :max="999"
              :disabled="!canEdit">
          </uni-number-box>
        </uni-forms-item>

        <uni-forms-item label="状态" name="status">
          <BottomSelect
              v-model="form.status"
              :options="statusOptions"
              :disabled="!canEdit"
              placeholder="请选择状态"
              title="选择状态">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="样式属性" name="cssClass">
          <uni-easyinput
              v-model="form.cssClass"
              placeholder="请输入样式属性"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注信息"
              :auto-height="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="handleSubmit">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addData, getData, updateData} from '@/api/system/dict/data'
import BottomSelect from '@/components/select/BottomSelect.vue'

const {proxy} = getCurrentInstance()

// 页面参数
const isEdit = ref(false)
const dictCode = ref('')
const dictType = ref('')
const dictName = ref('')
// 页面标题计算属性
const pageTitle = computed(() => {
  return isEdit.value ? '编辑字典数据' : '新增字典数据'
})
const submitting = ref(false)

// 计算属性：是否可以编辑
const canEdit = computed(() => {
  return !isEdit.value || isEdit.value // 新增模式或编辑模式都可以编辑
})

// 表单数据
const form = reactive({
  dictCode: undefined,
  dictLabel: '',
  dictValue: '',
  dictType: '',
  dictSort: 0,
  listClass: 'default',
  cssClass: '',
  status: '0',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  dictLabel: {
    rules: [
      {required: true, errorMessage: '请输入数据标签'},
      {minLength: 1, errorMessage: '数据标签至少1个字符'},
      {maxLength: 100, errorMessage: '数据标签不能超过100个字符'}
    ]
  },
  dictValue: {
    rules: [
      {required: true, errorMessage: '请输入数据键值'},
      {minLength: 1, errorMessage: '数据键值至少1个字符'},
      {maxLength: 100, errorMessage: '数据键值不能超过100个字符'}
    ]
  },
  dictSort: {
    rules: [
      {required: true, errorMessage: '请输入显示排序'}
    ]
  }
})

// 选项数据
const listClassOptions = ref([
  {value: 'default', text: '默认'},
  {value: 'primary', text: '主要'},
  {value: 'success', text: '成功'},
  {value: 'info', text: '信息'},
  {value: 'warning', text: '警告'},
  {value: 'danger', text: '危险'}
])

const cssClassOptions = ref([
  {value: '', text: '默认'},
  {value: 'text-red', text: '红色文字'},
  {value: 'text-green', text: '绿色文字'},
  {value: 'text-blue', text: '蓝色文字'},
  {value: 'text-orange', text: '橙色文字'},
  {value: 'text-purple', text: '紫色文字'}
])

const statusOptions = ref([
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
])

const formRef = ref()

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  dictType.value = options.dictType || ''
  dictName.value = options.dictName || ''
  form.dictType = dictType.value

  if (options.mode === 'edit' && options.dictCode) {
    isEdit.value = true
    dictCode.value = options.dictCode
    getDictInfo()
  } else {
    isEdit.value = false
  }

  // 设置页面标题
  const titleMap = {
    add: '新增字典数据',
    edit: '编辑字典数据',
    view: '查看字典数据'
  }
  uni.setNavigationBarTitle({
    title: titleMap[options.mode] || '字典数据管理'
  })
})

// 获取字典数据信息
async function getDictInfo() {
  try {
    const response = await getData(dictCode.value)
    if (response.code === 200) {
      Object.assign(form, response.data)
    } else {
      proxy.$modal.showToast(response.msg || '获取字典数据信息失败')
    }
  } catch (error) {
    console.error('获取字典数据信息失败:', error)
    proxy.$modal.showToast('获取字典数据信息失败')
  }
}

// 获取标签类型
function getTagType(listClass) {
  const typeMap = {
    'primary': 'primary',
    'success': 'success',
    'info': 'primary',
    'warning': 'warning',
    'danger': 'error',
    'default': 'default'
  }
  return typeMap[listClass] || 'default'
}

// 提交表单
async function handleSubmit() {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    submitting.value = true

    let response
    if (isEdit.value) {
      response = await updateData(form)
    } else {
      response = await addData(form)
    }

    if (response.code === 200) {
      proxy.$modal.showToast(isEdit.value ? '修改成功' : '新增成功')
      setTimeout(() => {
        handleBack()
      }, 1500)
    } else {
      proxy.$modal.showToast(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    proxy.$modal.showToast('操作失败')
  } finally {
    submitting.value = false
  }
}


// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

// 字典数据编辑页面特定样式
.dict-data-edit-page {
  // 可以添加字典数据特有的样式覆盖
}
</style>